<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>购物车 - 花间村</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            color: #333;
            padding-bottom: 120px; /* 为底部导航栏和结算栏留出空间 */
        }
        .container {
            max-width: 100%;
            padding: 15px;
        }
        .page-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            text-align: center;
        }
        .cart-empty {
            text-align: center;
            padding: 50px 0;
            color: #999;
        }
        .cart-empty-icon {
            font-size: 50px;
            margin-bottom: 15px;
        }
        .cart-item {
            background: #fff;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            display: flex;
            position: relative;
            align-items: center;
        }
        .cart-item-checkbox {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            cursor: pointer;
        }
        .cart-checkbox-wrapper {
            display: flex;
            align-items: center;
        }
        .cart-item-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 8px;
            margin-right: 15px;
        }
        .cart-item-info {
            flex: 1;
        }
        .cart-item-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 5px;
            color: #333;
        }
        .cart-item-price {
            font-size: 18px;
            color: #07C160;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .cart-item-quantity {
            display: flex;
            align-items: center;
        }
        .quantity-btn {
            width: 30px;
            height: 30px;
            background: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 5px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
        }
        .quantity-input {
            width: 40px;
            height: 30px;
            text-align: center;
            margin: 0 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        .cart-item-remove {
            position: absolute;
            top: 15px;
            right: 15px;
            color: #999;
            font-size: 20px;
            cursor: pointer;
        }
        .checkout-bar {
            position: fixed;
            bottom: 50px; /* 底部导航栏的高度 */
            left: 0;
            right: 0;
            height: 60px;
            background: #fff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 15px;
            box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
            z-index: 99;
        }
        .total-price {
            font-size: 18px;
            font-weight: bold;
        }
        .total-price-value {
            color: #07C160;
        }
        .checkout-btn {
            background-color: #07C160;
            color: white;
            border: none;
            border-radius: 25px;
            padding: 10px 25px;
            font-size: 16px;
            cursor: pointer;
        }
        .checkout-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 50px;
            background: #fff;
            display: flex;
            justify-content: space-around;
            align-items: center;
            box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
            z-index: 100;
        }
        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #666;
            font-size: 12px;
        }
        .nav-item.active {
            color: #07C160;
        }
        .nav-icon {
            font-size: 20px;
            margin-bottom: 2px;
        }
        .go-shopping-btn {
            background-color: #07C160;
            color: white;
            border: none;
            border-radius: 25px;
            padding: 10px 25px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <div class="page-title">购物车</div>
            @if(!empty($cartData))
                <button id="empty-cart-btn" style="background: none; border: 1px solid #ff4d4f; color: #ff4d4f; font-size: 16px; padding: 5px 12px; border-radius: 4px; cursor: pointer; font-weight: bold;">
                    清空购物车
                </button>
            @endif
        </div>
        
        @if(empty($cartData))
            <div class="cart-empty">
                <div class="cart-empty-icon">🛒</div>
                <div>购物车还是空的</div>
                <a href="{{ route('wechat.service.account.index') }}">
                    <button class="go-shopping-btn">去购物</button>
                </a>
            </div>
        @else
            <div class="checkout-bar" style="position: relative; bottom: auto; box-shadow: none; margin-bottom: 15px;">
                <div style="display: flex; align-items: center;">
                    <input type="checkbox" id="select-all" class="cart-item-checkbox" onclick="toggleSelectAll()">
                    <label for="select-all" style="margin-left: 5px; cursor: pointer;">全选</label>
                </div>
            </div>
            
            @foreach($cartData as $item)
                <div class="cart-item" data-id="{{ $item['id'] }}" data-price="{{ $item['product']->price }}" data-quantity="{{ $item['quantity'] }}">
                    <input type="checkbox" class="cart-item-checkbox item-checkbox" data-id="{{ $item['id'] }}" onclick="updateTotalPrice()">
                    @php
                        $images = $item['product']->images ?? [];
                        $firstImage = count($images) > 0 ? $images[0] : ($item['product']->media->first() ? $item['product']->media->first()->getUrl() : $item['product']->image_url);
                    @endphp
                    <img src="{{ $firstImage }}" class="cart-item-image" alt="{{ $item['product']->name }}" onerror="this.src='{{ asset('images/default_product.jpg') }}'">
                    <div class="cart-item-info">
                        <div class="cart-item-title">{{ $item['product']->name }}</div>
                        <div class="cart-item-price">¥{{ number_format($item['product']->price, 2) }}</div>
                        <div class="cart-item-quantity">
                            <button class="quantity-btn decrease-btn" onclick="updateQuantity('{{ $item['id'] }}', -1)">-</button>
                            <input type="number" class="quantity-input" value="{{ $item['quantity'] }}" min="1" max="{{ $item['product']->stock ?? 999 }}" onchange="updateQuantityInput('{{ $item['id'] }}', this.value)">
                            <button class="quantity-btn increase-btn" onclick="updateQuantity('{{ $item['id'] }}', 1)">+</button>
                        </div>
                    </div>
                    <div class="cart-item-remove" onclick="removeItem('{{ $item['id'] }}')">×</div>
                </div>
            @endforeach
            
            <div class="checkout-bar">
                <div class="total-price">
                    合计: <span class="total-price-value">¥0.00</span>
                </div>
                <button class="checkout-btn" id="checkout-button" onclick="checkout()" disabled>结算</button>
            </div>
        @endif
    </div>

    @include('wechat.service_account.components.bottom_nav')
    
    <script>
    // 预定义路由和令牌，避免在JavaScript中直接使用Blade语法
    const updateCartUrl = "{{ route('wechat.service.account.cart.update') }}";
    const removeCartItemUrl = "{{ route('wechat.service.account.cart.remove') }}";
    const emptyCartUrl = "{{ route('wechat.service.account.cart.empty') }}";
    const checkoutUrl = "{{ route('wechat.service.account.checkout') }}";
    const csrfToken = "{{ csrf_token() }}";
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        const emptyCartBtn = document.getElementById('empty-cart-btn');
        if (emptyCartBtn) {
            emptyCartBtn.addEventListener('click', emptyCart);
        }
        
        // 初始化商品数量数据
        updateTotalPrice();
    });
    
    // 更新选中商品的总价
    function updateTotalPrice() {
        let total = 0;
        let hasSelected = false;
        
        // 遍历所有选中的商品
        document.querySelectorAll('.item-checkbox:checked').forEach(checkbox => {
            const itemId = checkbox.getAttribute('data-id');
            const itemElement = document.querySelector(`.cart-item[data-id="${itemId}"]`);
            const price = parseFloat(itemElement.getAttribute('data-price'));
            const quantity = parseInt(itemElement.getAttribute('data-quantity'));
            
            total += price * quantity;
            hasSelected = true;
        });
        
        // 更新总价显示
        document.querySelector('.total-price-value').textContent = '¥' + total.toFixed(2);
        
        // 更新结算按钮状态
        const checkoutButton = document.getElementById('checkout-button');
        checkoutButton.disabled = !hasSelected || total <= 0;
    }
    
    // 切换全选状态
    function toggleSelectAll() {
        const selectAllCheckbox = document.getElementById('select-all');
        const isChecked = selectAllCheckbox.checked;
        
        // 更新所有商品的选中状态
        document.querySelectorAll('.item-checkbox').forEach(checkbox => {
            checkbox.checked = isChecked;
        });
        
        // 更新总价和结算按钮状态
        updateTotalPrice();
    }
    
    // 清空购物车函数
    function emptyCart() {
        if (confirm('确定要清空购物车吗？此操作不可撤销。')) {
            fetch(emptyCartUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({})
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 清空成功，刷新页面
                    location.reload();
                } else {
                    alert(data.message || '清空购物车失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('清空购物车失败，请重试');
            });
        }
    }
    
    function updateQuantity(cartItemId, change) {
        const inputElement = document.querySelector(`.cart-item[data-id="${cartItemId}"] .quantity-input`);
        let newQuantity = parseInt(inputElement.value) + change;
        
        // 确保数量不小于1
        if (newQuantity < 1) newQuantity = 1;
        
        // 确保数量不超过库存
        const maxStock = parseInt(inputElement.getAttribute('max'));
        if (newQuantity > maxStock) newQuantity = maxStock;
        
        inputElement.value = newQuantity;
        
        // 发送请求更新购物车
        updateCart(cartItemId, newQuantity);
    }
    
    function updateQuantityInput(cartItemId, value) {
        let newQuantity = parseInt(value);
        const inputElement = document.querySelector(`.cart-item[data-id="${cartItemId}"] .quantity-input`);
        
        // 确保数量不小于1
        if (newQuantity < 1) {
            newQuantity = 1;
            inputElement.value = 1;
        }
        
        // 确保数量不超过库存
        const maxStock = parseInt(inputElement.getAttribute('max'));
        if (newQuantity > maxStock) {
            newQuantity = maxStock;
            inputElement.value = maxStock;
        }
        
        // 发送请求更新购物车
        updateCart(cartItemId, newQuantity);
    }
    
    function updateCart(cartItemId, quantity) {
        // 更新本地数据
        const itemElement = document.querySelector(`.cart-item[data-id="${cartItemId}"]`);
        if (itemElement) {
            itemElement.setAttribute('data-quantity', quantity);
            
            // 如果商品被选中，更新总价
            const checkbox = document.querySelector(`.item-checkbox[data-id="${cartItemId}"]`);
            if (checkbox && checkbox.checked) {
                updateTotalPrice();
            }
        }
        
        fetch(updateCartUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken
            },
            body: JSON.stringify({
                cart_item_id: cartItemId,
                quantity: quantity
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新成功，刷新页面以更新总价
                location.reload();
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('更新购物车失败，请重试');
        });
    }
    
    function removeItem(cartItemId) {
        if (confirm('确定要从购物车中移除此商品吗？')) {
            fetch(removeCartItemUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({
                    cart_item_id: cartItemId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 移除成功，刷新页面
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('移除商品失败，请重试');
            });
        }
    }
    
    function checkout() {
        // 获取所有选中的商品ID
        const selectedItems = [];
        document.querySelectorAll('.item-checkbox:checked').forEach(checkbox => {
            selectedItems.push(checkbox.getAttribute('data-id'));
        });
        
        // 将选中的商品ID存储到sessionStorage
        sessionStorage.setItem('selectedCartItems', JSON.stringify(selectedItems));
        
        // 跳转到结算页面
        window.location.href = checkoutUrl;
    }
    </script>
</body>
</html>